package com.es.poem.controller;

import com.es.poem.config.ResultInfo;
import com.es.poem.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.List;
import java.util.Objects;


/**
 * @description: 热词操作
 **/
@RestController
@RequestMapping("/dic")
public class DicController {

    private static final String ES_HOTWORDS = "es-hotwords";

    private static final Logger logger = LoggerFactory.getLogger(DicController.class);

    @Autowired
    private RedisUtil redisUtil;


    //读取数据，并放入redis中
    @GetMapping("fileReader")
    public ResultInfo fileReader() {
        ResultInfo resultInfo = new ResultInfo();

        List<Object> objectList = redisUtil.lGet(ES_HOTWORDS, 0, -1);
        if (Objects.isNull(objectList) || objectList.size() == 0) {
            String path = this.getClass().getClassLoader().getResource("static/txt/hotwords.txt").getPath();
            try {
                FileReader reader = new FileReader(path);
                BufferedReader br = new BufferedReader(reader);
                String line;
                while ((line = br.readLine()) != null) {
                    objectList.add(line.trim());
                }
                //放入redis
                redisUtil.lSet(ES_HOTWORDS, objectList);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultInfo.success(objectList,objectList.size());
    }

    //写入数据，并放入redis中
    @GetMapping("fileWrite")
    public ResultInfo fileWrite(@RequestParam("value") String value) {
        ResultInfo resultInfo = new ResultInfo();
        if (Objects.isNull(value) || "".equals(value.trim())) {
            return resultInfo.error("不允许为空");
        }

        List<Object> objectList = redisUtil.lGet(ES_HOTWORDS, 0, -1);
        boolean contains = objectList.contains(value.trim());
        if (contains) {
            return resultInfo.error("该数据已存在");
        }
        //写入
        boolean b = writeToResource(value.trim());
        if (b) {
            objectList.add(value.trim());
            redisUtil.lSet(ES_HOTWORDS, value.trim());
        }
        return resultInfo.success(objectList);
    }


    //写入数据，并放入redis中
    //策略：先复制再删除，最后重命名
    @GetMapping("fileDelete")
    public ResultInfo fileDelete(@RequestParam("value") String value) {
        ResultInfo resultInfo = new ResultInfo();
        String path = this.getClass().getClassLoader().getResource("static/txt/hotwords.txt").getPath();
        String pathNew = path.substring(0, path.lastIndexOf("/") + 1) + "hotwords-new.txt";
        File file = new File(path);
        File fileNew = new File(pathNew);
        //保证文件存在
        ensureDirectory(pathNew);
        boolean flag=true;
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            BufferedWriter bw = new BufferedWriter(new FileWriter(pathNew));
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().equals(value.trim())) {
                    //移除redis中list的元素
                    redisUtil.lRemove(ES_HOTWORDS, 1, value.trim());
                    continue;
                }
                bw.write(line);
                bw.newLine();
                bw.flush();
            }
            bw.close();
            br.close();
            flag=true;
        } catch (Exception e) {
            //删除
            fileNew.delete();
            //redis
            redisUtil.lSet(ES_HOTWORDS, value.trim());

            flag=false;
            e.printStackTrace();
        }

        if(flag){
            //删除
            file.delete();
            //新文件重命名为hotwords.txt
            file = new File(path);
            fileNew.renameTo(file);
        }

        return resultInfo.success();
    }


    public boolean writeToResource(String value) {
        String resourcePath = this.getClass().getClassLoader().getResource("static/txt/hotwords.txt").getPath();
        // 保证目录一定存在
        ensureDirectory(resourcePath);
        System.out.println("resourcePath = " + resourcePath);

        boolean flag = true;
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(resourcePath), true))); // 追加的方法
            //写入：\r 是回车、\n 是换行
            //Unix系统里，每行结尾只有“<换行>”，即“\n”；
            //Windows系统里面，每行结尾是“<回车><换行>”，即“\r\n”；
            //Mac系统里，每行结尾是“<回车>”,即“\r”。
            StringBuffer buffer = new StringBuffer(value + "\r\n");
            out.write(buffer.toString());
        } catch (IOException e) {
            flag = false;
            logger.error("FileUtil write exception", e);
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }


    /**
     * 保证拷贝的文件的目录一定要存在
     *
     * @param filePath 文件路径
     */
    public static void ensureDirectory(String filePath) {
        if (Objects.isNull(filePath)) {
            return;
        }
        filePath = replaceSeparator(filePath);
        if (filePath.indexOf("/") != -1) {
            filePath = filePath.substring(0, filePath.lastIndexOf("/"));
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
    }

    /**
     * 将符号“\\”和“\”替换成“/”,有时候便于统一的处理路径的分隔符,避免同一个路径出现两个或三种不同的分隔符
     *
     * @param str
     * @return
     */
    public static String replaceSeparator(String str) {
        return str.replace("\\", "/").replace("\\\\", "/");
    }
}
